package myservlet.control;

import mybean.data.Account_Bean;

import java.io.*;
import java.sql.*;
import java.text.MessageFormat;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

@WebServlet("/insertServlet")
public class AccountAdd extends HttpServlet {
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Account_Bean resultBean = null;
        try {
            resultBean = (Account_Bean) request.getAttribute("resultBean");
            if (resultBean == null) {
                resultBean = new Account_Bean(); //创建Javabean对象
                HttpSession session = request.getSession();
                session.setAttribute("resultBean", resultBean);
            }
        } catch (Exception exp) {
            resultBean = new Account_Bean();  //创建Javabean对象
            HttpSession session = request.getSession();
            session.setAttribute("resultBean", resultBean);
        }
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
        }
        request.setCharacterEncoding("gb2312");
        String dataBase = request.getParameter("dataBase");
        String tableName = request.getParameter("tableName");
        String username = request.getParameter("username");
        String pass = request.getParameter("pass");
        String surePass = request.getParameter("surePass");

//        System.out.println("username: " + username);
//        System.out.println("password: " + pass);

        if (username == null || pass.length() == 0 || surePass.length() == 0) {
            fail(request, response, "未填写信息，清重新输入");
            return;
        }

        if (!pass.equals(surePass)) {
            fail(request, response, "密码和确认密码不一致");
            return;
        }

        if (username.length() > 30 || pass.length() > 30) {
            fail(request, response, "用户名或密码过长");
            return;
        }


        resultBean.setUsername(username);
        resultBean.setPassword(pass);


        String str_username = "'" + username + "'";
        String str_pass = "'" + pass + "'";


        String condition = MessageFormat.format(
                "INSERT INTO {0}(username,password) VALUES ({1},{2})",
                tableName, str_username, str_pass);

        Connection con;
        Statement sql;
        ResultSet rs;
        try {
            String uri = "jdbc:mysql://127.0.0.1/" + dataBase + "?" +
                    "user=root&password=root&characterEncoding=gb2312";
            con = DriverManager.getConnection(uri);
            // 判断一下是否唯一

            String only = "select * from acount where username = '"+username+ "'";
            sql=con.createStatement();
            ResultSet only_rs =sql.executeQuery(only);
            boolean m= only_rs.next();
            if(m == true){
                fail(request, response, "用户名已存在，请换一个用户名吧");
            } else {
                try {
                    sql = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                            ResultSet.CONCUR_READ_ONLY);
                    sql.executeUpdate(condition);
                    response.sendRedirect("/Vice_School_ShopWeb_war_exploded/member/add_success.jsp");
                } catch (SQLException e){
                    System.out.println(e);
                    fail(request, response, "添加记录失败:" + e.toString());
                }
            }
//            RequestDispatcher dispatcher = request.getRequestDispatcher("/member/add_success.jsp");
//            dispatcher.forward(request, response);

        } catch (SQLException e) {
            System.out.println(username + "该用户名已经存在!");
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void fail(HttpServletRequest request, HttpServletResponse response,
                     String backNews) {
        response.setContentType("text/html;charset=GB2312");
        try {
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head><style>body{text-align: center;background: antiquewhite;margin:300px}</style></head>");
            out.println("<body>");
            out.println("<h2>" + backNews + "</h2>");
            out.println("返回");
            out.println("<a href = /Vice_School_ShopWeb_war_exploded/member/register.jsp>注册页面</a>");
            out.println("</body></html>");
        } catch (IOException exp) {
        }
    }
}